package actors

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

import DB._
import akka.actor._
import akka.pattern.AskableActorSelection
import akka.util.Timeout
import common.Tool._
import common._
import play.api.libs.concurrent.Akka
import scala.collection.mutable.ListBuffer
import scala.concurrent.Await
import scala.concurrent.duration._
import play.api.Play.current
import common.JedisCacheKeys._

/**
 * Created by 林 on 14-4-10.
 */


class TaskServer extends Actor with ActorLogging {
  val tasks: ListBuffer[AddTask] = new ListBuffer()
  implicit val timeout = Timeout(60 seconds)
  def getActor(path: String) = {
    val actorFuture = Akka.system.actorSelection(path)
    val asker = new AskableActorSelection(actorFuture)
    val fut = asker.ask(new Identify(1))
    val ident = Await.result(fut, timeout.duration).asInstanceOf[ActorIdentity]
    ident.getRef
  }

  //Actors
  lazy val  cacheServer=getActor("/user/cache_server_actor")

  def receive = {
    case s: LoopTaskMessage => //定时任务
      safe {
        val dateTime = Calendar.getInstance()
        dateTime.setTime(new Date())
        val List(hour, minute, second) = List(dateTime.get(Calendar.HOUR_OF_DAY), dateTime.get(Calendar.MINUTE), dateTime.get(Calendar.SECOND))
        if (second % 50 == 0) {//更新缓存数据
          cacheServer ! SETTING_MESSAGE_KEY
          cacheServer ! TABLE_CACHE_KEY
          cleanCache
        }
        if(second % 50 ==0 && hour==1 &&minute==0){
          cacheServer ! WEIXIN_ID_CACHE_KEY
        }
        val loopList = tasks.filter(_ != null)
        tasks.clear()
        loopList.foreach(t =>
          if (t.time == 1) {
            t.actor ! t.message
          } else tasks append t.copy(time = t.time - 1)
        )
      }
      Thread.sleep(1000)
      self ! new LoopTaskMessage
    case at: AddTask =>
      tasks.append(at)
    case uq: UnSupportQueryExcepiton =>
      log.error(uq, "收到一个来自自身或者其他服务的不支持请求")
    case a: Any =>
      sender ! new UnSupportExcepiton
  }
}

case class LoopTaskMessage()

case class AddTask(val actor: ActorRef, val message: Any, val time: Int, val cron: String)

case class CountTask(val id:String, val uid:String,val aid:String,val oaid:String,val host:String)

case class AdcTask(val id:String, val uid:String,val aid:String,val uuid:String)

case class CacheValue(val key:String,val value:String)

class CacheTaskServer extends Actor with ActorLogging {

  def updateTableCache(f: => Map[Any,Any],key:String)={
    safe {
      val datas = f
      if (datas.size > 0) JedisTool.useJedis(_.hmset(key, datas))
    }
  }
  def cacheTable[T](f: => List[T],fid: T=> AnyRef,key:String)={
    val datas=f
    setCache(key,datas,Int.MaxValue)
    datas.foreach(v=>setCache(key+(fid(v)),v.asInstanceOf[AnyRef],Int.MaxValue))
  }

  def receive = {
    case SETTING_MESSAGE_KEY =>
      updateTableCache(new Setting().queryAll.map(s => s.name -> s.value).toMap,SETTING_VALUE_CACHE_KEY)
    case TABLE_CACHE_KEY=>
      updateTableCache(new App().queryAll.map(s => s.id.toString -> s.name).toMap,APP_TABLE_CACHE_KEY)
    case INIT_CACHE_KEY=>
      cacheTable[App](new App().queryAll,_.id.toString,APP_TABLE_CACHE_KEY)
    case WEIXIN_ID_CACHE_KEY =>
      safe {
        new App().queryAll().foreach{a=>
          updateTableCache(new UserConnect().query(s"appid=${a.id}").map(v => v.token -> v.uid).toMap, WEIXIN_ID_CACHE_KEY+a.id)
        }
      }

    case CacheValue(k,v)=>
      safe{
        Tool.delCache(k+v)
        k match{
          case _=>
        }
      }
    case uq: UnSupportQueryExcepiton =>
      log.error(uq, "收到一个来自自身或者其他服务的不支持请求")
    case a: Any =>
      sender ! new UnSupportExcepiton
  }
}

class DbTaskServer extends Actor with ActorLogging {
  def receive = {
    case at: DBEntity =>
      safe {
        at.insert()
      }
    case sql:String=>
        safe{
          DBEntity.sql(sql)
        }
    case uq: UnSupportQueryExcepiton =>
      log.error(uq, "收到一个来自自身或者其他服务的不支持请求")
    case a: Any =>
      sender ! new UnSupportExcepiton
  }
}
